from datetime import datetime

from django.shortcuts import render
from pyexpat.errors import messages
from rest_framework import status, generics, permissions
from rest_framework.views import APIView
from . import serializers
from .authentications import generate_jwt
from apps.oaauth.serializers import LoginSerializer,UserSerializer
from rest_framework.response import Response
from apps.oaauth.models import OAUser, UserStatusChoices
from .serializers import ResetPwdSerializer

# Create your views here.
class LoginView(APIView):
    def post(self, request):
        #1.验证数据是否可用
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data['user']
            user.last_login = datetime.now()
            user.save()
            token = generate_jwt(user)
            return Response({'token': token,'user':UserSerializer(user).data})
        else:
            print(serializer.errors)
            #两个数组包着，所以先转换为列表然后[0][0]
            detail = list(serializer.errors.values())[0][0]
            return Response({"detail":detail},status=status.HTTP_400_BAD_REQUEST)

class ResetPasswordView(APIView):
    def post(self, request):
        serializer = ResetPwdSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            pwd1 = serializer.validated_data['pwd1']
            request.user.set_password(pwd1)
            request.user.save()
            return Response()
        else:
            print(serializer.errors)
            detail = list(serializer.errors.values())[0][0]
            return Response({"detail":detail},status=status.HTTP_400_BAD_REQUEST)

# class LoginView(generics.CreateAPIView,
#                 generics.UpdateAPIView,
#                 generics.DestroyAPIView,
#                 generics.RetrieveAPIView):
#     serializer_class = LoginSerializer
#     queryset = OAUser.objects.all()
#
#     def create(self, request, *args, **kwargs):
#         # 使用序列化器验证输入数据
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#
#         # 获取经过验证的用户
#         user = serializer.validated_data['user']
#
#         # 更新用户的最后登录时间
#         user.last_login = datetime.now()
#         user.save()
#
#         # 生成 JWT
#         token = generate_jwt(user)
#
#         # 返回 JWT
#         return Response({'token': token}, status=status.HTTP_200_OK)


